package com.saascloud.auth.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * @author liangxuch
 * 客户端配置
 */
@EnableResourceServer
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class ResouceServerConfig extends ResourceServerConfigurerAdapter  {
    @Autowired
    OAuthConfig oauthConfig;
    @Autowired
    TokenStore tokenStore;
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private OAuth2WebSecurityExpressionHandler expressionHandler;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        // 401跳转，当用户请求了一个受保护的资源，但是用户没有通过认证
        resources.authenticationEntryPoint(authenticationEntryPoint);
        // 403返回json
        resources.accessDeniedHandler(accessDeniedHandler);
        // SPEL
        resources.expressionHandler(expressionHandler);
        // 客户端id
        resources.resourceId(oauthConfig.getClientId())
                .tokenStore(tokenStore)
                .stateless(true);

    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // .antMatchers("/login", "/portal", "/api/**").permitAll()  放行

                .anyRequest().access("@myAuthorityPermit.hasAuthority(request, authentication)") // 动态授权
                // .anyRequest().authenticated()
                .and().csrf().disable() // 关闭csrf
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 关闭session
                .and().cors();
    }


}

